package com.htfyun;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;

import com.htfyun.utils.DebugLog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by sst on 2017/11/27.
 */

public enum ScanInstalledAppManager {
    INSTANCE;


    private List<IScanOverListener> overListenerList = new CopyOnWriteArrayList<>();

    private MyLoader myLoader;

    public void addOverListener(IScanOverListener listener) {

        if (!overListenerList.contains(listener)) {
            overListenerList.add(listener);
        }

    }

    public void removeOverListener(IScanOverListener listener) {
        overListenerList.remove(listener);
    }

    public void init(Activity activity) {
        myLoader = new MyLoader(activity.getApplicationContext(), this);

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);

        activity.getApplicationContext().registerReceiver(mReceiver, filter);
                
        new Thread(myLoader).start();
    }

    public void deInit(Activity activity) {

        activity.getApplicationContext().unregisterReceiver(mReceiver);

    }
    
    
    public boolean isScanOver() {
        if (myLoader == null) {
            return false;
        }

        return myLoader.isScanOver();
        
    }
    public List<AppInfo> getAppInfoList() {
        if (myLoader == null) {
            return Collections.emptyList();
        }

        return myLoader.getAppInfoList();
    }

    private BroadcastReceiver mReceiver  = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            final String action = intent.getAction();
            if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {

                String packageName = intent.getData().getSchemeSpecificPart();
                DebugLog.e("package added packageName = " + packageName);

                ResolveInfo info = findAppByPackageName(context, packageName);
                if (info != null) {

                    String activityName = info.activityInfo.name; // 获得该应用程序的启动Activity的name  
                    String pkgName = info.activityInfo.packageName; // 获得应用程序的包名  

                    String appLabel = (String) info.loadLabel(context.getPackageManager()); // 获得应用程序的Label  
                    Drawable icon = info.loadIcon(context.getPackageManager()); // 获得应用程序图标  
                    // 为应用程序的启动Activity 准备Intent  
                    Intent launchIntent = new Intent();
                    launchIntent.setComponent(new ComponentName(pkgName,
                            activityName));
                    // 创建一个AppInfo对象，并赋值  
                    AppInfo appInfo = new AppInfo();
                    appInfo.setAppLabel(appLabel);
                    appInfo.setPkgName(pkgName);
                    appInfo.setAppIcon(icon);
                    appInfo.setIntent(launchIntent);
                    getAppInfoList().add(appInfo); // 添加至列表中  


                    Collections.sort(getAppInfoList(), new Comparator<AppInfo>() {
                        @Override
                        public int compare(AppInfo appInfo1, AppInfo appInfo2) {
                            return appInfo1.getAppLabel().compareTo(appInfo2.getAppLabel());
                        }
                    });

                }

            } else if (action.equals(Intent.ACTION_PACKAGE_REPLACED)) {

                String packageName = intent.getData().getSchemeSpecificPart();

                List<AppInfo> appInfoList = getAppInfoList();

                Iterator<AppInfo> iter = appInfoList.iterator();
                while (iter.hasNext()) {
                    AppInfo item = iter.next();
                    if (item.getPkgName().equals(packageName)) {
                        iter.remove();
                    }
                }

                
                ResolveInfo info = findAppByPackageName(context, packageName);
                if (info != null) {

                    String activityName = info.activityInfo.name; // 获得该应用程序的启动Activity的name  
                    String pkgName = info.activityInfo.packageName; // 获得应用程序的包名  

                    String appLabel = (String) info.loadLabel(context.getPackageManager()); // 获得应用程序的Label  
                    Drawable icon = info.loadIcon(context.getPackageManager()); // 获得应用程序图标  
                    // 为应用程序的启动Activity 准备Intent  
                    Intent launchIntent = new Intent();
                    launchIntent.setComponent(new ComponentName(pkgName,
                            activityName));
                    // 创建一个AppInfo对象，并赋值  
                    AppInfo appInfo = new AppInfo();
                    appInfo.setAppLabel(appLabel);
                    appInfo.setPkgName(pkgName);
                    appInfo.setAppIcon(icon);
                    appInfo.setIntent(launchIntent);
                    getAppInfoList().add(appInfo); // 添加至列表中  


                    Collections.sort(getAppInfoList(), new Comparator<AppInfo>() {
                        @Override
                        public int compare(AppInfo appInfo1, AppInfo appInfo2) {
                            return appInfo1.getAppLabel().compareTo(appInfo2.getAppLabel());
                        }
                    });

                }


            } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {

                String packageName = intent.getData().getSchemeSpecificPart();

                List<AppInfo> appInfoList = getAppInfoList();

                Iterator<AppInfo> iter = appInfoList.iterator();
                while (iter.hasNext()) {
                    AppInfo item = iter.next();
                    if (item.getPkgName().equals(packageName)) {
                        iter.remove();
                    }
                }

            }

            for (IScanOverListener listener : overListenerList) {
                listener.onOver();
            }

        }
        
        
    };

    public static ResolveInfo findAppByPackageName(Context context, String mPackageName) {
        ResolveInfo newAppInfo = null;
        // 用于存放临时应用程序  
        List<ResolveInfo> mTempAllApps;

        PackageManager TempPackageManager = context.getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        mainIntent.setPackage(mPackageName);
        mTempAllApps = TempPackageManager.queryIntentActivities(mainIntent, 0);
        newAppInfo = mTempAllApps.get(0);

        return newAppInfo;
    }

    private static class MyLoader implements Runnable {


        private final Context context;
        private final PackageManager pm;

        private final WeakReference<ScanInstalledAppManager> scanReference;

        private List<AppInfo> appInfoList;

        private AtomicBoolean isScanOver = new AtomicBoolean();

        public MyLoader(Context context, ScanInstalledAppManager manager) {
            this.context = context;
            pm = context.getPackageManager();

            appInfoList = new ArrayList<>();

            scanReference = new WeakReference<ScanInstalledAppManager>(manager);

        }

        public boolean isScanOver() {
            return isScanOver.get();
        }

        public void setScanOver(boolean scanOver) {
            isScanOver.set(scanOver);
        }

        public List<AppInfo> getAppInfoList() {
            return appInfoList;
        }


        @Override
        public void run() {

            setScanOver(false);

            queryAppInfo();

            setScanOver(true);

            ScanInstalledAppManager manager = scanReference.get();
            if (manager != null) {

                for (IScanOverListener l : manager.overListenerList
                        ) {

                    l.onOver();
                }
            }
        }

        // 获得所有启动Activity的信息，类似于Launch界面  
        public void queryAppInfo() {
            PackageManager pm = this.pm; // 获得PackageManager对象  
            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            // 通过查询，获得所有ResolveInfo对象.  
            List<ResolveInfo> resolveInfos = pm
                    .queryIntentActivities(mainIntent, 0);//PackageManager.MATCH_DEFAULT_ONLY);
            // 调用系统排序 ， 根据name排序  
            // 该排序很重要，否则只能显示系统应用，而不能列出第三方应用程序  
            Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(pm));
            if (appInfoList != null) {
                appInfoList.clear();
                for (ResolveInfo reInfo : resolveInfos) {
                    String activityName = reInfo.activityInfo.name; // 获得该应用程序的启动Activity的name  
                    String pkgName = reInfo.activityInfo.packageName; // 获得应用程序的包名  
//                    DebugLog.e("pkgName = " + pkgName);

                    try {

                        if (pkgName.contains(pm.getPackageInfo(context.getPackageName(), 0).packageName)) {
                            continue;
                        }

                    } catch (Exception e) {
                        
                    }
                  
                    String appLabel = (String) reInfo.loadLabel(pm); // 获得应用程序的Label  
                    Drawable icon = reInfo.loadIcon(pm); // 获得应用程序图标  
                    // 为应用程序的启动Activity 准备Intent  
                    Intent launchIntent = new Intent();
                    launchIntent.setComponent(new ComponentName(pkgName,
                            activityName));
                    // 创建一个AppInfo对象，并赋值  
                    AppInfo appInfo = new AppInfo();
                    appInfo.setAppLabel(appLabel);
                    appInfo.setPkgName(pkgName);
                    appInfo.setAppIcon(icon);
                    appInfo.setIntent(launchIntent);
                    appInfoList.add(appInfo); // 添加至列表中  

                }
            }


            
        }
    }

//        public List<AppInfo> getAppInfos(){
//            //创建要返回的集合对象
//            List<AppInfo> appInfos = new ArrayList<>();
//            //获取手机中所有安装的应用集合
//            List<ApplicationInfo> applicationInfos = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
//            //遍历所有的应用集合
//            for(ApplicationInfo info : applicationInfos){
//
//                AppInfo appInfo = new AppInfo();
//
//                //获取应用程序的图标
//                Drawable app_icon = info.loadIcon(pm);
//                appInfo.setApp_icon(app_icon);
//
//                //获取应用的名称
//                String app_name = info.loadLabel(pm).toString();
//                appInfo.setApp_name(app_name);
//
//                //获取应用的包名
//                String packageName = info.packageName;
//                appInfo.setPackagename(packageName);
//              
//                //判断应用程序是否是用户程序
//                appInfos.add(appInfo);
//            }
//            return appInfos;
//        }
//    }
    


}
